<template>
    <div class="upload-box">
        <draggable v-model="videoList"  chosenClass="chosen" forceFallback="true" group="group1" animation="0" handle=".mover">
            <transition-group>
                <div class="photo-item mover" v-for="item in videoList" :key="item.uid || item.id" :style="'width:'+itemWidth+'px;height:'+itemHeight+'px;'">
                    <el-image :src="item.photo">
                        <div slot="error" class="image-slot">
                            <i class="el-icon-video-camera"></i>
                        </div>
                    </el-image>

                    <el-tooltip class="btn btn-link" effect="dark" placement="top" v-if="item.videoUrlList">
                        <div slot="content" v-html="getVideoAllUrl(item)"></div>
                        <i class="el-icon-link"></i>
                    </el-tooltip>

                    <i class="el-icon-refresh-right btn btn-get-video-info" @click="getVideoPlayInfo(item, 1000)"></i>
                    <i class="el-icon-video-play btn btn-zoom-in" v-if="!item.isUploading && item.videoUrlList" @click="handlePlayVideo(item)"></i>
                    <i class="el-icon-delete btn btn-delete" @click="handleRemove(item)"></i>

                    <i class="el-icon-loading btn btn-loading" v-if="item.isUploading"></i>
                    <div class="loading-loaded-percent" v-if="item.isUploading">上传中 {{item.loadedPercent}}%</div>
                    <div class="loading-loaded-percent" v-if="!item.isUploading && !item.videoUrlList">视频转码中</div>
                </div>

                <div class="photo-item" :key="0" :style="'width:'+itemWidth+'px;height:'+itemHeight+'px;'" v-show="fileLimit > valueList.length">
                    <el-upload
                        action="https://xxxxx"
                        accept=".mp4,.MP4,.mov,.MOV,.ogg,.OGG,.flv,.FLV,.rmvb,.RMVB,.wma,.WMA,.wmv,.WMV"
                        :show-file-list="false"
                        :http-request="handleSubmitUpload"
                        :on-exceed="handleOnLimit"
                        :multiple="false"
                        :file-list="valueList"
                        :limit="fileLimit"
                        v-if="showUploadObj"
                    >
                      <i class="el-icon-plus"></i>
                    </el-upload>
                </div>
            </transition-group>
        </draggable>

        <el-dialog :visible.sync="dialogVisible" :modal="false" class="video-play-box">
            <div class="prism-player" id="J_prismPlayer"></div>
        </el-dialog>
    </div>
</template>

<script>
import { createUploadVideo, refreshUploadVideo, getVideoPlayInfo } from '@/api/video'
import draggable from 'vuedraggable'
export default {
	name: 'UploadVideo',
    components: { draggable },
	props: {
        valueList: {
        	type: Array,
        	default: []
        },
        fileLimit: {
        	type: [String, Number],
        	default: 1000
        },
        itemWidth: {
            type: [String, Number],
            default: 135
        },
        itemHeight: {
            type: [String, Number],
            default: 135
        }
	},
	data() {
		return {
            dialogVisible: false,
            dialogImageUrl: '',
            videoList: this.valueList,
            uploader: null,
            aliUserId: '1296128129554451',
            aliRegionId: 'cn-shenzhen',
            aliVideoServer: 'https://outin-3237456103f011ec875e00163e021072.oss-cn-shenzhen.aliyuncs.com/',
            player: null,
            getVideoPlayInfoTimer: null
		}
	},
	watch: {
        valueList: function() {
            this.videoList = this.valueList
        },
        videoList: function() {
            this.$emit('update:valueList', this.videoList)
        }
	},
    computed: {
    	showUploadObj(){
    	    console.log('showUploadObj', this.valueList.length, this.fileLimit)
    	    return this.valueList.length < this.fileLimit
    	}
    },
    created() {
    	console.log('upload-video-created')
        this.uploader = this.createUploader()
    },
	methods: {
        handleCheckFileExists(fileName) {
            this.videoList.forEach(function (item, index) {
                if (item.photo.indexOf(fileName) > -1) {
                    return true
                } else if (item.name && item.name.indexOf(fileName) > -1) {
                    return true
                }
            });
            return false
		},
        handleClose() {
            console.log('handleClose')
			this.dialogVisible = false
		},
        handleRemove(file) {
            // console.log('file', file);
            // console.log('fileList', this.videoList);
            for (let i = 0; i < this.videoList.length; i++) {
                if ( (file.id && file.id == this.videoList[i].id) ||
                    (file.uid && file.uid == this.videoList[i].uid)
                ) {
                    this.videoList.splice(i, 1)
                    return
                }
            }
        },
        handlePlayVideo(file) {
            // console.log('file', file)
            // console.log('fileList', this.value);
            let that = this
            if (that.player) {
                that.player.dispose()
            }
            that.dialogVisible = true;
            that.$nextTick(() => {
            	that.player = new Aliplayer({
            	    id: "J_prismPlayer",
            	    // autoplay: true,
            	    width: "640px",
            	    height: "480px",
            	    // vid:"06619fe267f54c83b9d1274dff1f0c48",
            	    // playauth:'',
            	    cover: file.photo,
            	    source: file.videoUrlList[0].playUrl
            	});
            })
        },
        handleOnLimit(file, fileList) {
            console.log('fileList', fileList);
            this.$message.error('最多只能上传[' + this.fileLimit + ']个视频')
        },
        handleSubmitUpload(param) {
            let that = this
            let file = param.file
            // this.$refs.upload.submit();
            console.log('file', file);

            if (that.handleCheckFileExists(file.name)) {
                that.$message.error('视频[' + file.name + ']已存在，不需要重复上传')
                return
            }

            let fileItem = {
                uid: file.uid,
                name: file.name,
                photo: '',
                videoUrlList: null,
                isUploading: 1,
                loadedPercent: 0
            };
            that.videoList.push(fileItem)

            console.log('submitUpload......');
            // return
            that.uploader.addFile(file, null, null, null, '{"Vod":{}}')
        },
        createUploader() {
            let that = this
            let uploader = new AliyunUpload.Vod({
                //阿里账号ID，必须有值
                userId: that.aliUserId,
                //上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
                region: that.aliRegionId,
                //分片大小默认1 MB，不能小于100 KB
                partSize: 1048576,
                //并行上传分片个数，默认5
                parallel: 5,
                //网络原因失败时，重新上传次数，默认为3
                retryCount: 3,
                //网络原因失败时，重新上传间隔时间，默认为2秒
                retryDuration: 2,
                // 添加文件成功
                'addFileSuccess': function (uploadInfo) {
                    console.log("addFileSuccess: ", uploadInfo)
                    uploader.startUpload()
                },
                //开始上传
                'onUploadstarted': function (uploadInfo) {
                    console.log("onUploadstarted: ", uploadInfo)
                    if (uploadInfo.videoId) {
                        refreshUploadVideo({videoId: uploadInfo.videoId}).then((res) => {
                            uploader.setUploadAuthAndAddress(uploadInfo, res.data.UploadAuth, res.data.UploadAddress);
                        })
                    } else {
                        createUploadVideo({fileName: uploadInfo.file.name, title: uploadInfo.file.name}).then((res) => {
                        	uploader.setUploadAuthAndAddress(uploadInfo, res.data.UploadAuth, res.data.UploadAddress, res.data.VideoId)
                        })
                    }
                },
                //文件上传成功
                'onUploadSucceed': function (uploadInfo) {
                    console.log("onUploadSucceed: ", uploadInfo)
                    that.videoList.forEach(function (item, index) {
                        if (item.uid && item.uid == uploadInfo.file.uid) {
                            item.isUploading = 0
                            item.videoId = uploadInfo.videoId
                            that.getVideoPlayInfo(item)
                            // console.log('onUploadSucceed: fileList', that.value)
                            return
                        }
                    });
                },
                //文件上传失败
                'onUploadFailed': function (uploadInfo, code, message) {
                    console.log("onUploadFailed: ", uploadInfo, code, message)
                    that.$message.error('上传时发生错误[' + message + ']')
                    that.handleRemove(uploadInfo.file)
                },
                //文件上传进度，单位：字节
                'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
                    console.log("onUploadProgress: ", uploadInfo, totalSize, loadedPercent)
                    // that.loadedPercent[uploadInfo.file.uid] = Math.ceil(loadedPercent * 100)
                    // console.log("onUploadProgress: ", that.loadedPercent)

                    that.videoList.forEach(function (item, index) {
                        if (item.uid && item.uid == uploadInfo.file.uid) {
                            item.loadedPercent = Math.ceil(loadedPercent * 100)
                            return
                        }
                    });
                },
                //上传凭证或STS token超时
                'onUploadTokenExpired': function (uploadInfo) {
                    console.log("onUploadTokenExpired: ", uploadInfo)
                    refreshUploadVideo({videoId: uploadInfo.videoId}).then((res) => {
                        uploader.resumeUploadWithAuth(res.data.UploadAuth);
                    })
                },
                //全部文件上传结束
                'onUploadEnd':function(uploadInfo){
                    console.log("onUploadEnd: ", uploadInfo)
                }
            });
            return uploader
        },
        getVideoPlayInfo(item, times) {
            times = times || 10000
            if (!item.tryCount) {
                item.tryCount = 0
            }
            item.tryCount++
            let that = this
            clearTimeout(that.getVideoPlayInfoTimer)
            that.getVideoPlayInfoTimer = setTimeout(function(){
                getVideoPlayInfo({videoId: item.videoId}).then((res) => {
                    // debugger
                	if (res.data.duration && res.data.photo && res.data.videoUrlList && res.data.videoUrlList.length > 0) {
                        item.duration = res.data.duration
                        item.photo = res.data.photo
                        item.videoUrlList = res.data.videoUrlList
                    } else if (item.tryCount <= 360) {
                        that.getVideoPlayInfo(item)
                    }
                }).catch(err => {
                    console.log('getVideoPlayInfo', err)
                    that.getVideoPlayInfo(item)
                })
            }, times);
        },
        getVideoAllUrl(item) {
            let urls = item.photo
            item.videoUrlList.forEach(function (row, index) {
                urls += '<br/>' + row.playUrl
            });
            return urls
        }
	}
}
</script>

<style lang="scss" scoped>

</style>
